package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *拦截前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截本地之外的访问
       /* if (request.getRemoteAddr().startsWith("192.168")){
             return false;
        }*/
        //获取用户登录信息
        Object employee = request.getSession().getAttribute("employee");
        //判断是否登录
        if (employee != null) {
            //往线程中存储数据
            BaseContext.setCurrentId((Long)employee);
            //不为null表示已登录,放行
            return true;
        }
        //获取员工登录信息
        Object userId = request.getSession().getAttribute("user");
        //判断是否登录
        if (userId!=null){
            //往线程中存储数据
            BaseContext.setCurrentId((Long)userId);
            //不为null表示已登录,放行
            return true;
        }
        //为null表示未登录,拦截下来
        //响应数据给前端页面
        //由于前端接收json数据,将响应数据 NOTLOGIN 转为json数据
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        //拦截
        return false;
    }

    /**
     * 最终处理
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //线程结束时,清理当前线程的数据
        BaseContext.removeCurrentId();
    }
}
